//
//  LTLModel.m
//  WeiBo
//
//  Created by LiTaiLiang on 16/9/19.
//  Copyright © 2016年 LTL. All rights reserved.
//

#import "LTLModel.h"

#define Document [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"user.plist"]

@interface LTLModel ()

@end

@implementation LTLModel
/**
 判断时间是否过期而是否返回令牌

 @return 令牌
 */
-(NSString *)access_token
{
    //获取现在的时间
    NSDate *time = [NSDate date];
    //和过期时间对比
    NSComparisonResult result = [self.expires_time compare:time];
    if (result) {     //过期时间大于现在时间  令牌没有过期 给令牌
        
        return _access_token;
        
    } else {          //过期时间小于现在时间  令牌过期 不给令牌
        
        return  nil;
        
    }
}
//初始化
-(instancetype)initWhetDict : (NSDictionary *)dict
{
    if ((self = [super init]) != nil) {
        
//      [self setValuesForKeysWithDictionary:dict];
        self.expires_in = [dict[@"expires_in"] doubleValue];
        self.access_token = dict[@"access_token"];
        self.uid = dict[@"uid"];
        //赋值计算过期时间
        self.expires_time = [NSDate dateWithTimeIntervalSinceNow:self.expires_in];
    }
    return self;
}
//初始化
+(instancetype)LTLModelInitDict :(NSDictionary *)dict
{
    return [[self alloc]initWhetDict:dict];
}
//归档初始化方法
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder
{
    if ((self = [super init]) != nil) {
        self.name = [aDecoder decodeObjectForKey:@"name"];
        self.avatar_hd = [aDecoder decodeObjectForKey:@"avatar_hd"];
        self.access_token = [aDecoder decodeObjectForKey:@"access_token"];
        self.expires_in = [aDecoder decodeDoubleForKey:@"expires_in"];
        self.uid = [aDecoder decodeObjectForKey:@"uid"];
        self.expires_time = [aDecoder decodeObjectForKey:@"expires_time"];
        
    }
    return self;
}
////归档时调用此方法
- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeObject:self.avatar_hd forKey:@"avatar_hd"];
    [aCoder encodeObject:self.access_token forKey:@"access_token"];
    [aCoder encodeDouble:self.expires_in forKey:@"expires_in"];
    [aCoder encodeObject:self.uid forKey:@"uid"];
    [aCoder encodeObject:self.expires_time forKey:@"expires_time"] ;
//    [aCoder encodeConditionalObject:self.expires_time forKey:@"expires_time"];
}
/**
 *  存储归档
 */
-(void)file
{
    //通过归档储存
    [NSKeyedArchiver archiveRootObject:self toFile:Document];
}
/**
 *  读取归档
 *
 *  @return 归档
 */
+(instancetype)read
{
    //解挡
    return [NSKeyedUnarchiver unarchiveObjectWithFile:Document];
}
@end
